﻿using System.Collections.Specialized;
using DBFile.Core.Interfaces;
using DBFile.Providers.Impl;

namespace DBFile.Providers
{
	public class SqlServerProvider : DBFileProviderBase
	{
        protected override string ProviderDescription
        {
            get { return ProviderDescriptionMessage; }
        }

		protected override void OnAfterInitialize(NameValueCollection config)
		{
            ConnectionString = GetConnectionString(config, ConnectionStringNameKey, ConnectionStringNameMissingMessage, ConnectionStringMissingMessage);
            UseStoredProcedures = GetConfigSettingAsBool(config, UseStoredProceduresKey);
            UseFileStreams = GetConfigSettingAsBool(config, UseFileStreamsKey);
		}

        protected override IDBFileProvider Provider
        {
            get
            {
                lock (padLock)
                {
                    if (_provider == null)
                    {
                        _provider = CreateProvider(ConnectionString, UseStoredProcedures, UseFileStreams);
                    }
                }
                return _provider;
            }
        }

        private static IDBFileProvider CreateProvider(string connectionString, bool useStoredProcedures, bool useFileStreams)
        {
            if (useFileStreams)
            {
                return new Sql2008FileStreams(connectionString);
            }
            else if (useStoredProcedures)
            {
                return new StoredProcedure(connectionString);
            }
            return new StaticSql(connectionString);
        }

        internal string ConnectionString { get; private set; }
        internal bool UseStoredProcedures { get; private set; }
        internal bool UseFileStreams { get; private set; }

        private const string ProviderDescriptionMessage = "SqlServer DBFile Provider";
        private const string UseStoredProceduresKey = "useStoredProcedures";
        private const string UseFileStreamsKey = "useFileStreams";
        private const string ConnectionStringNameKey = "connectionStringName";
        private const string ConnectionStringNameMissingMessage = "Connection string name is not specified";
        private const string ConnectionStringMissingMessage = "Connection string is not found";
	}
}
